#define _CRT_SECURE_NO_WARNINGS
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        ListNode* a = headA, * b = headB;
        int lenA = 0, lenB = 0;
        while (a != NULL) {
            lenA++;
            a = a->next;
        }
        while (b != NULL) {
            lenB++;
            b = b->next;
        }
        a = headA, b = headB;
        if (lenA < lenB) {
            swap(a, b);
            swap(lenA, lenB);
        }
        int diff = lenA - lenB;
        while (diff--) a = a->next;
        while (a != NULL && b != NULL) {
            if (a == b) return a;
            else {
                a = a->next;
                b = b->next;
            }
        }
        return NULL;
    }
};